package org.android.SuperList;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class EditaGastos extends Activity 
{
	
	private EditText etxGASTO;	
	private Long ID_GASTO;
	private DbAdapter mDbHelper;
	
	protected void onCreate(Bundle savedInstaceState)
	{
		super.onCreate(savedInstaceState);
		mDbHelper= new DbAdapter(this);
		mDbHelper.open();
		setContentView(R.layout.editagastos);
		etxGASTO = (EditText) findViewById(R.id.etxgasto);		
		Button btnAceptar = (Button) findViewById(R.id.btnaceptargasto);
		
		ID_GASTO = savedInstaceState != null ? savedInstaceState.getLong(DbAdapter.ID) :null;
		
		if (ID_GASTO == null) 
		{
			Bundle extras = getIntent().getExtras();            
			ID_GASTO = extras != null ? extras.getLong(DbAdapter.ID): null;
		}
		
		btnAceptar.setOnClickListener(new View.OnClickListener()		
		{
			public void onClick(View view)
			{
				GuardaDatos();
				setResult(RESULT_OK);
				finish();
			}			
		}			
		);			
	}
	
	private void CargaInformacion()
	{
		if(ID_GASTO != null)
		{
			Cursor Lista = mDbHelper.RecuperaRegistros(DbAdapter.TABLA_GASTOS,ID_GASTO);
			startManagingCursor(Lista);
			etxGASTO.setText(Lista.getString(Lista.getColumnIndexOrThrow(DbAdapter.GASTO)));					
		}		
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) 
    {
        super.onSaveInstanceState(outState);
        outState.putLong(DbAdapter.ID, ID_GASTO);
    }
    
	@Override
    protected void onResume() 
    {
        super.onResume();
        CargaInformacion();
    }

	@Override
	protected void onPause()
	{
		super.onPause();				
		mDbHelper.close();
				
	}
	
	private void GuardaDatos()
	{
		try
		{
		String[] Valores;				
		if(ID_GASTO == null)
		{
			Valores = new String[]{null,etxGASTO.getText().toString()};
			long id= mDbHelper.creaRegistro(DbAdapter.TABLA_GASTOS,Valores);
			if(id>0)
			{
				ID_GASTO=id;
			}
		}
		else
		{	
			Valores = new String[]{ID_GASTO.toString(),etxGASTO.getText().toString()};
			mDbHelper.actualizaRegistro(DbAdapter.TABLA_GASTOS,Valores);
		}	
		}
		catch(Exception E)
		{}
	}

}
